题目

输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。为简单起见,标点符号和普通字母一样处理。例如输入字符串”I am a student. “,则输出”student. a am I”。

输入: "the sky is blue"
输出: "blue is sky the"

解答

思路

使用双指针记录需要反转的单词的左右边界。重点是对空格的处理。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
string reverseWords(string s) {
int n = s.length(), l = n-1, r;
string res = "";
while(l >= 0 && s[l] == ' ') --l; // 先排除尾部所有空格
r = l;
while(l >= 0){ // 从末尾第一个不为空格的字符开始遍历
while(l >= 0 && s[l] != ' ') --l; // 找到单词的左边界
res.append(s.substr(l+1, r-l)); // 记录当前找到的单词
res.append(" "); // 加空格分割
while(l >= 0 && s[l] == ' ') l--; // 跳过中间的空格
r = l; // 下一个单词的右边界
}
res.pop_back(); // 去掉尾部多加的一个空格
return res;
}
};

复杂度

  • 时间复杂度 O(N)
  • 空间复杂度 O(1)